import './Inspection.scss'
import './Scss/Inspection.scss'
import { Gauge, Column } from '@ant-design/plots'
import { useEffect, useRef, useState } from 'react'
import { useMount, useRequest, useSetState, useSize } from 'ahooks'

import { Http } from '../../../../Common/Api'
import { project } from '../../../../Common/Data'
import { FrontModalBox } from '../Modal'
import { GaugeA01Template } from './AssetsCharts'

const { imageUrl } = project[window.location.hostname]

export const Inspection001 = ({ org, height }) => {
    const [Data, setData] = useState([
        { uuid: '1', title: '下单数', value: 0, color: '#D7E492' },
        { uuid: '2', title: '已整改', value: 0, color: '#97FFC8' },
        { uuid: '3', title: '合格数', value: 0, color: '#8FD6FF' },
    ])

    const { runAsync: getSecurityStat } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            const { ok, submitted, handled, handling, notOk } = res
            const one = handling + notOk + ok + handled + submitted
            const two = handling + notOk + ok
            const thr = handled + submitted

            setChartsData({ percent: two / one })
            setData([
                { uuid: '1', title: '下单数', state: '', value: one, color: '#6CEFDC', icon: '下单数量.png' },
                { uuid: '2', title: '已整改', state: '', value: two, color: '#6CD2EF', icon: '已整改.png' },
                { uuid: '3', title: '未整改', state: '', value: thr, color: '#99FFE6', icon: '整改中.png' },
            ])
        },
    })

    const [ChartsData, setChartsData] = useSetState({
        autoFit: false,
        height: height || 100,
        percent: 0.86,
        radius: 0.9,
        startAngle: Math.PI,
        endAngle: 2 * Math.PI,
        range: { color: ['l(0) 0:#F28159 1:#ADEEBA', 'rgba(58, 168, 226, 0.2)'], width: 27 },
        indicator: null,
        statistic: {
            title: {
                offsetY: -25,
                style: { fontSize: '35px', color: '#fff', fontWeight: 'bold', fontFamily: 'Bahnschrift' },
                formatter: ({ percent }) => ` ${(percent * 100).toFixed(0)}%`,
            },
            content: {
                style: { fontSize: '16px', color: '#60EAFF', fontWeight: 'bold', fontFamily: 'PingFang' },
                formatter: () => '整改率',
            },
        },
        gaugeStyle: { lineCap: 'round' },
    })

    useEffect(() => {
        getSecurityStat({ url: 'getSecurityStat', data: { organizationUuid: org || '' } })
    }, [getSecurityStat, org])

    const [OptionsCall, setOptionsCall] = useState()

    return (
        <div className="Inspection001">
            <Gauge {...ChartsData} />
            <div
                className="Table"
                onClick={() => {
                    if (org) {
                        setOptionsCall({
                            type: 'TableList',
                            data: {
                                title: '安全巡检统计',
                                type: 'SecondaryInspectionTemplate',
                                OrganizationUuid: org,
                            },
                        })
                    }
                }}
            >
                {Data.map(({ uuid, title, value, color }) => (
                    <div key={uuid}>
                        <div style={{ color }}>{title}</div>
                        <div>{value} 项</div>
                    </div>
                ))}
            </div>
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const InspectionA01 = ({ type }) => {
    const List = [
        { uuid: 1, label: '下单数', color: '#00F3DC', value: 'A01', icon: '下单数.png' },
        { uuid: 2, label: '已整改', color: '#38D5F3', value: 'A02', icon: '已整改.png' },
        { uuid: 3, label: '未整改', color: '#FFEE8C', value: 'A03', icon: '整改中.png' },
    ]

    const [Data, setData] = useState({})
    const [ChartsData, setChartsData] = useState()
    const [OptionsCall, setOptionsCall] = useState()

    const { runAsync: getA01 } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            const { handledCount, handlingCount, lateNum, notOkCount, okCount, submittedCount } = res
            const A01 = handlingCount + notOkCount + okCount + handledCount + submittedCount
            const A02 = handlingCount + notOkCount + okCount
            const A03 = handledCount + submittedCount
            setData({ lateNum, A01, A02, A03 })
            setChartsData({
                autoFit: false,
                height: 110,
                percent: A02 / A01 || 0,
                radius: 0.9,
                startAngle: Math.PI,
                endAngle: 2 * Math.PI,
                range: { color: ['l(0) 0:#F28159 1:#ADEEBA', 'rgba(58, 168, 226, 0.2)'], width: 27 },
                indicator: null,
                statistic: {
                    title: {
                        offsetY: -24,
                        style: { fontSize: '32px', color: '#fff', fontWeight: 'bold', fontFamily: 'Bahnschrift' },
                        formatter: ({ percent }) => ` ${(percent * 100).toFixed(0)}%`,
                    },
                    content: {
                        style: { fontSize: '16px', color: '#60EAFF', fontWeight: 'bold', fontFamily: 'PingFang' },
                        formatter: () => '整改完成率',
                    },
                },
                gaugeStyle: { lineCap: 'round' },
            })
        },
    })
    const mapping = {
        security: {
            text: '安全',
            get: 'getJSZXSecurityStat',
            table: 'SecondaryInspectionTemplate',
            late: 'LateList',
        },
        quality: {
            text: '质量',
            get: 'getQualityCheckStat',
            table: 'QualityInspectionTemplate',
            late: 'QualityLateList',
        },
    }

    const { text, table, late } = mapping[type]
    useMount(() => {
        getA01({ url: mapping[type].get })
    })

    return (
        <div className="InspectionA01">
            <div className="top">
                <div
                    onClick={() => {
                        setOptionsCall({ type: 'TableList', data: { title: `${text}巡检`, type: table } })
                    }}
                >
                    {ChartsData && <Gauge {...ChartsData} />}
                </div>
                <div
                    onClick={() => {
                        setOptionsCall({ type: 'TableList', data: { title: `${text}巡检本月逾期信息`, type: late } })
                    }}
                >
                    <img src={imageUrl + 'waring.png'} alt="" />
                    <div>
                        <div>本月总逾期</div>
                        <div>{Data.lateNum ?? 0}</div>
                    </div>
                </div>
            </div>
            <div className="btm">
                {List.map(({ uuid, label, value, color, icon }) => (
                    <div key={uuid}>
                        <img src={imageUrl + icon} alt="" />
                        <div>
                            <div style={{ color }}>{label}</div>
                            <div>{Data[value] ?? 0}</div>
                        </div>
                    </div>
                ))}
            </div>
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

const ColumnCharts = (size, data) => {
    const { width, height } = size
    return {
        autoFit: false,
        width,
        height,
        data,
        maxColumnWidth: 16,
        appendPadding: 24,
        isGroup: true,
        xField: 'type',
        yField: 'value',
        seriesField: 'name',
        color: ['#B3FCFE', '#71A8FF'],
        legend: {
            layout: 'horizontal',
            position: 'top',
            offsetY: 24,
            itemName: { style: { fill: '#B2FBFD', fontSize: 12 } },
        },

        xAxis: {
            label: { style: { fill: '#B2FBFD' } },
            line: { style: { stroke: '#B2FBFD' } },
            tickLine: { style: { stroke: '#B2FBFD' } },
        },
        yAxis: {
            title: { text: '数量', position: 'end', autoRotate: false, offset: 50, style: { fill: '#B2FBFD' } },
            tickCount: 5,
            label: { style: { fill: '#B2FBFD' } },
            grid: { line: { style: { stroke: 'rgba(178, 251, 253, 0.2)', lineDash: [8, 2] } } },
        },
    }
}

//
export const InspectionA02 = ({ type }) => {
    const Charts = useRef()
    const size = useSize(Charts)
    const [Data, setData] = useState()
    const [OptionsCall, setOptionsCall] = useState()

    const mapping = {
        security: {
            text: '安全',
            get: 'getSecurityGetSecurityByOrg',
            table: 'SecondaryInspectionTemplate',
        },
        quality: {
            text: '质量',
            get: 'getQualityGetSecurityByOrg',
            table: 'QualityInspectionTemplate',
        },
    }
    const { runAsync: getA01 } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setData(
                res.list
                    .map(({ uuid, tableName, totalCount, handledCount }) => [
                        { uuid, name: '下单数', type: tableName, value: totalCount },
                        { uuid, name: '已整改', type: tableName, value: handledCount },
                    ])
                    .flat(),
            )
        },
    })
    const { text, table } = mapping[type]
    useMount(() => {
        getA01({ url: mapping[type].get })
    })
    return (
        <div className="InspectionA02" ref={Charts}>
            {size && Data && (
                <Column
                    {...ColumnCharts(size, Data)}
                    onReady={plot =>
                        plot.on('plot:click', e => {
                            const { x, y } = e
                            const [{ data }] = plot.chart.getTooltipItems({ x, y })
                            const { uuid: OrganizationUuid } = data
                            setOptionsCall({
                                type: 'TableList',
                                data: { title: `${text}巡检`, type: table, OrganizationUuid },
                            })
                        })
                    }
                />
            )}
            <FrontModalBox OptionsCall={OptionsCall} />
        </div>
    )
}

export const InspectionA03 = ({ list, width, height, url }) => {
    const [percent, setPercent] = useState(0)
    const [Data, setData] = useState()

    const { runAsync } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setPercent(res.整改率)
            setData(res)
        },
    })

    useMount(() => {
        runAsync({ url })
    })

    return (
        <div className="InspectionA03">
            <div>
                <GaugeA01Template size={{ width, height }} data={percent} title="整改率" />
            </div>
            <div style={{ width: `${width + 40}px` }}>
                {list.map(({ uuid, label, value, unit, color }) => (
                    <div key={uuid}>
                        <div style={{ color }}>{label}</div>
                        <div>
                            {Data ? Data[value] : 0} {unit}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    )
}
